package com.seckill.service.impl;

import com.seckill.domain.Blacklist;
import com.seckill.domain.User;
import com.seckill.mapper.BlacklistMapper;
import com.seckill.mapper.UserMapper;
import com.seckill.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    private static final String SECRET_KEY = "seckillSecretKey123456";
    private static final long EXPIRATION = 1000 * 60 * 60 * 24; // 1天

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlacklistMapper blacklistMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    public void loadBlacklistToRedis() {
        java.util.List<com.seckill.domain.Blacklist> all = blacklistMapper.findAll();
        for (com.seckill.domain.Blacklist b : all) {
            if (b.getUserId() != null) {
                redisTemplate.opsForSet().add("blacklist:userId", String.valueOf(b.getUserId()));
            }
            if (b.getIpAddress() != null) {
                redisTemplate.opsForSet().add("blacklist:ip", b.getIpAddress());
            }
            if (b.getDeviceId() != null) {
                redisTemplate.opsForSet().add("blacklist:deviceId", b.getDeviceId());
            }
        }
    }

    @Override
    public String login(String username, String password, String ip, String deviceId) {
        User user = userMapper.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 生成token
        String token = Jwts.builder()
                .setSubject(user.getId().toString())
                .claim("username", user.getUsername())
                .claim("vipLevel", user.getVipLevel())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        user.setToken(token);

        return token;
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /**
     * 检查用户是否符合秒杀资格（如VIP等级、黑名单）
     * @param username 用户名
     * @param ipAddress IP地址
     * @param deviceId 设备ID
     * @return true-有资格，false-无资格
     */
    @Override
    public boolean checkSeckillQualification(String username, String ipAddress, String deviceId) {
        User user = userMapper.findByUsername(username);
        if (user == null || user.getVipLevel() == null || user.getVipLevel() < 1) {
            return false;
        }
        String userIdStr = String.valueOf(user.getId());
        Boolean isBlackUser = redisTemplate.opsForSet().isMember("blacklist:userId", userIdStr);
        Boolean isBlackIp = ipAddress != null && !ipAddress.isEmpty()
                ? redisTemplate.opsForSet().isMember("blacklist:ip", ipAddress)
                : false;
        Boolean isBlackDevice = deviceId != null && !deviceId.isEmpty()
                ? redisTemplate.opsForSet().isMember("blacklist:deviceId", deviceId)
                : false;
        if (Boolean.TRUE.equals(isBlackUser) || Boolean.TRUE.equals(isBlackIp) || Boolean.TRUE.equals(isBlackDevice)) {
            return false;
        }
        return true;
    }
} 